#include <sys/epoll.h>
#include <cerrno>
#include <cstring>
#include "Log.hpp"

class Epoll
{
public:
    // 成功返回0，失败返回-1
    static int Epoll_create(int size)
    {
        int epfd = epoll_create(size);
        if(epfd == -1)
        {
            Messagelog(ERROR, "epoll create error: %d:%s", errno, strerror(errno));
            return -1;
        }
        Messagelog(DEBUG, "epoll create successful epfd: %d", epfd);
        return epfd;
    }

    // op: EPOLL_CTL_ADD... event: EPOLLIN...
    static bool Epoll_ctl(int epfd, int op, int fd, uint32_t event)
    {
        epoll_data_t data;
        data.fd = fd;
        struct epoll_event ep_event;
        ep_event.data = data;
        ep_event.events = event;
        if(-1 == epoll_ctl(epfd, op, fd, &ep_event))
        {
            Messagelog(ERROR, "epoll ctl error: %d:%s", errno, strerror(errno));
            return false;
        }
        Messagelog(DEBUG, "epoll ctl succerssful fd: %d", fd);
        return true;
    }

    static int Epoll_wait(int epfd, struct epoll_event events[], int max_events, int timeout)
    {
        int size = epoll_wait(epfd, events, max_events, timeout);
        if(size < 0)
        {
            Messagelog(ERROR, "epoll ctl error: %d:%s", errno, strerror(errno));
        }
        else if(size == 0)
        {
            Messagelog(DEBUG, "time out ...");
        }
        return size;
    }
};